import baseRequest from "@/common/js/request.js"
export default {
  data() {
    return {
      remoteRes: null
    }
  },
  computed: {
    remoteData(){
		const v = this
		if (!v.remoteRes || (v.data.config.remoteDataPath && v.data.config.remoteDataPath.endsWith('.'))) {
			return []
		}
		if (v.data.config.remoteDataPath) {
			return eval(`v.remoteRes.${v.data.config.remoteDataPath}`);
		} else {
			if (typeof v.remoteRes === 'object') {
				return v.remoteRes.data || v.remoteRes
			} else {
				return v.remoteRes
			}
		}
    }
  },
  watch: {
		'data.config.remoteUrl': function(){
			if (this.data.config.isRemote) {
				this.getRemoteData();
			}
		}
  },
  created() {
		if (this.data.config.isRemote) {
			this.getRemoteData();
		}
  },
  methods: {
    getRemoteData() {
		let remoteUrl = this.data.config.remoteUrl, v = this;
		if (remoteUrl) {
			if (remoteUrl.startsWith("/") || remoteUrl.startsWith(v.$config.base_url)){
				// 本站链接，可能需要登录验证
				if (v.formInfo) {
					for (const key in v.formInfo) {
						let value = v.formInfo[key]
						if (typeof value != 'undefined') {
							remoteUrl+= (remoteUrl.indexOf('?')==-1?'?':'&')+key+'='+value
						}
					}
				}
				baseRequest(remoteUrl).then(res => {
					v.remoteRes = res
				}).catch(err => {
					console.log(err);
				})
			} else {
				// 外站链接
				baseRequest(remoteUrl).then(res => {
						if (res.status === 200) {
						  v.remoteRes = res.data
						} else {
						  this.$u.toast(`status: ${res.status}, statusText: ${res.statusText}`)
						}
				}).catch(err => {
						this.$u.toast(err);
				})
			}
		}
    }
  }
}